package org.malred.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.malred.common.CustomException;
import org.malred.entity.Category;
import org.malred.entity.Dish;
import org.malred.entity.Setmeal;
import org.malred.mapper.CategoryMapper;
import org.malred.service.CategoryService;
import org.malred.service.DishService;
import org.malred.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl
        extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类, 删除之前判断
     *
     * @param id
     * @return
     */
    @Override
    public void remove(Long id) {
        // 根据分类id查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int count = dishService.count(dishLambdaQueryWrapper);
        // 是否关联菜品, 是 -> error
        if (count > 0) {
            throw new CustomException("当前分类下关联了菜品, 不能删除");
        }
        // 查询是否关联套餐
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        count = setmealService.count(setmealLambdaQueryWrapper);
        // 是否关联套餐, 是 -> error
        if (count > 0) {
            throw new CustomException("当前分类下关联了套餐, 不能删除");
        }
        // 正常删除
        super.removeById(id);
    }
}
